package kr.or.smardi.smardi_AScan.User;

import java.util.*;

import kr.or.smardi.smardi_AScan.*;
import kr.or.smardi.smardi_AScan.Help.*;
import kr.or.smardi.smardi_AScan.Scan.*;
import kr.or.smardi.smardi_AScan.db.*;
import android.app.*;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.*;
import android.database.*;
import android.graphics.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;

public class AC_UserAdd extends Activity {

	EditText m_name;
	TextView m_birth;

	TextView txt_explain_firstRegist;

	TextView txt_name, txt_gender, txt_birth;
	TextView edit_gender, edit_birth;
	LinearLayout layout_gender, layout_birth;

	// 상단 타이틀바
	RelativeLayout titleBar = null;
	ImageButton btn_TopLeft = null;
	ImageButton btn_TopRight = null;
	TextView txt_subTitle = null;

	// 탭 메뉴
	LinearLayout tabMenu = null;
	ImageButton tab_measure = null;
	ImageButton tab_record = null;
	ImageButton tab_user = null;
	ImageButton tab_help = null;

	String gender = null; // 성별을 표시
	String birthday = null; // 생일을 표시

	DB_Adapter db_Adapter;
	Manage_SharedPreference mPref;

	Calendar calDateTime = Calendar.getInstance();

	boolean isFirstUserAdd = false; // 처음으로 유저를 생성하는지.

	private AlertDialog m_adlgConnectionInfo = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_add);

		db_Adapter = new DB_Adapter(AC_UserAdd.this);
		db_Adapter.open();

		mPref = new Manage_SharedPreference(AC_UserAdd.this);

		m_name = (EditText) findViewById(R.id.edit_name);
		m_birth = (TextView) findViewById(R.id.txt_birth);

		txt_name = (TextView) findViewById(R.id.txt_name);
		txt_gender = (TextView) findViewById(R.id.txt_gender);
		txt_birth = (TextView) findViewById(R.id.txt_birth);
		edit_gender = (TextView) findViewById(R.id.edit_gender);
		edit_birth = (TextView) findViewById(R.id.edit_birth);

		layout_gender = (LinearLayout) findViewById(R.id.layout_input_gender);
		layout_birth = (LinearLayout) findViewById(R.id.layout_input_birth);

		// 영어로 전환한다
		/*
		 * if (getString(R.string.language).equals("en") == true) {
		 * m_male.setImageDrawable(getResources().getDrawable(
		 * R.drawable.check_male_0_en));
		 * m_female.setImageDrawable(getResources().getDrawable(
		 * R.drawable.check_female_0_en)); }
		 */
		// 타이틀바 세팅
		titleBar = (RelativeLayout) findViewById(R.id.inc_title_bar);
		btn_TopLeft = (ImageButton) titleBar.findViewById(R.id.btn_top_left);
		btn_TopRight = (ImageButton) titleBar.findViewById(R.id.btn_top_right);
		txt_subTitle = (TextView) findViewById(R.id.txt_subTitle);
		txt_subTitle.setText(getString(R.string.subTitle_user_add));

		// 탭 세팅--------------------------
		tabMenu = (LinearLayout) findViewById(R.id.inc_tab_menu);
		tab_measure = (ImageButton) findViewById(R.id.tab_measure);
		tab_record = (ImageButton) findViewById(R.id.tab_record);
		tab_user = (ImageButton) findViewById(R.id.tab_user);
		tab_user.setImageDrawable(getResources().getDrawable(
				R.drawable.tab_user_1));
		tab_help = (ImageButton) findViewById(R.id.tab_help);

		// 탭 세팅 끝--------------------------

		txt_explain_firstRegist = (TextView) findViewById(R.id.txt_explain_firstRegist);

		// 폰트를 바꾼다.
		changeFont();

		registButtonEvents();

		if (mPref.getUserName().equals("")) {
			// 사용자 이름이 없으면 처음으로 사용자를 만드는 것으로 판단
			isFirstUserAdd = true;

			// 탭을 지운다
			tabMenu.setVisibility(View.GONE);

			txt_explain_firstRegist
					.setText(getString(R.string.explain_firstRegist));

			// exit 버튼을 둔다.
			btn_TopLeft.setImageDrawable(getResources().getDrawable(
					R.drawable.c_btn_exit));
		} else {
			txt_explain_firstRegist
					.setText(getString(R.string.userAdd_explain));

			// back 버튼을 둔다.
			btn_TopLeft.setImageDrawable(getResources().getDrawable(
					R.drawable.c_btn_back));
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		db_Adapter.close();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			finish();
			overridePendingTransition(R.anim.fadein, R.anim.fadeout);
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 폰트를 적용한다.
	 */
	private void changeFont() {
		Typeface tf = Typeface.createFromAsset(getAssets(),
				"fonts/Daum_Regular.ttf");

		txt_subTitle.setTypeface(tf);
		txt_explain_firstRegist.setTypeface(tf);
		m_name.setTypeface(tf);
		m_birth.setTypeface(tf);

		txt_name.setTypeface(tf);
		txt_gender.setTypeface(tf);
		txt_birth.setTypeface(tf);

		edit_gender.setTypeface(tf);
		edit_birth.setTypeface(tf);
	}

	private void registButtonEvents() {

		// 생일 선택
		layout_birth.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new DatePickerDialog(AC_UserAdd.this, dateSetListener,
						calDateTime.get(Calendar.YEAR), calDateTime
								.get(Calendar.MONTH), calDateTime
								.get(Calendar.DAY_OF_MONTH)).show();
			}
		});

		// 성별 선택
		layout_gender.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (m_adlgConnectionInfo != null) {
					m_adlgConnectionInfo.dismiss();
				}

				LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
				View view = inflater.inflate(R.layout.dialog_gender, null);
				TextView txt_male = (TextView) view
						.findViewById(R.id.gender_male);
				TextView txt_female = (TextView) view
						.findViewById(R.id.gender_female);

				m_adlgConnectionInfo = new AlertDialog.Builder(AC_UserAdd.this)
						.setView(view)
						.setTitle(getString(R.string.prompt_gender))
						/*
						 * .setNegativeButton(getString(R.string.dialog_Cancel),
						 * new DialogInterface.OnClickListener() {
						 * 
						 * @Override public void onClick(DialogInterface dialog,
						 * int which) { dialog.dismiss(); } })
						 */.create();

				m_adlgConnectionInfo.show();

				txt_male.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						gender = "Male";
						edit_gender.setText(getString(R.string.male));
						m_adlgConnectionInfo.dismiss();
					}
				});

				txt_female.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						gender = "Female";
						edit_gender.setText(getString(R.string.female));
						m_adlgConnectionInfo.dismiss();
					}
				});
			}
		});

		// 성별 선택
		/*
		 * m_male.setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { //영어로 전환한다
		 * if(getString(R.string.language).equals("en") == true) {
		 * m_male.setImageDrawable
		 * (getResources().getDrawable(R.drawable.check_male_1_en));
		 * m_female.setImageDrawable
		 * (getResources().getDrawable(R.drawable.check_female_0_en)); } else {
		 * m_male
		 * .setImageDrawable(getResources().getDrawable(R.drawable.check_male_1
		 * )); m_female.setImageDrawable(getResources().getDrawable(R.drawable.
		 * check_female_0)); }
		 * 
		 * gender = "Male"; } });
		 * 
		 * m_female.setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { //영어로 전환한다
		 * if(getString(R.string.language).equals("en") == true) {
		 * m_male.setImageDrawable
		 * (getResources().getDrawable(R.drawable.check_male_0_en));
		 * m_female.setImageDrawable
		 * (getResources().getDrawable(R.drawable.check_female_1_en)); } else {
		 * m_male
		 * .setImageDrawable(getResources().getDrawable(R.drawable.check_male_0
		 * )); m_female.setImageDrawable(getResources().getDrawable(R.drawable.
		 * check_female_1)); }
		 * 
		 * gender = "Female"; } });
		 */

		btn_TopLeft.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
				overridePendingTransition(R.anim.fadein, R.anim.fadeout);
			}
		});

		btn_TopRight.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				boolean isOK = checkImformation(); // 유효성 검증

				Builder alert = new AlertDialog.Builder(AC_UserAdd.this);
				alert.setTitle(R.string.userAdd_dialog_confirm_title)
						.setMessage(R.string.userAdd_dialog_confirm_message)
						.setPositiveButton(
								R.string.userAdd_dialog_confirm_positive,
								new Dialog.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										addUserToDatabase(); // 데이터베이스에 사용자 추가

										if (isFirstUserAdd == true) {
											startActivity(new Intent(
													AC_UserAdd.this,
													AC_Scan_main.class));
											mPref.setCheckedTutorial(true);
										} else {
											startActivity(new Intent(
													AC_UserAdd.this,
													AC_UserMain.class));
										}

										finish();
										overridePendingTransition(
												R.anim.fadein, R.anim.fadeout);
									}
								})
						.setNegativeButton(
								R.string.userAdd_dialog_confirm_negative,
								new Dialog.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								});

				if (isOK) {
					alert.show();
				}
			}
		});

		// ------------------------------------------------------------
		// Tab menu events

		tab_measure.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(AC_UserAdd.this, AC_Scan_main.class);
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.fadein, R.anim.fadeout);
			}
		});

		tab_record.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				/*
				 * Intent intent = new Intent(AC_UserAdd.this,
				 * AC_RecordMain.class); startActivity(intent); finish();
				 * overridePendingTransition(R.anim.fadein, R.anim.fadeout);
				 */
			}
		});

		tab_help.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(AC_UserAdd.this, AC_Help_main.class);
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.fadein, R.anim.fadeout);
			}
		});
	}

	protected void addUserToDatabase() {
		String user_name = m_name.getText().toString();
		String user_gender = gender;
		String user_birthday = birthday;

		long addedUserUid = db_Adapter.addUser(user_name, user_gender,
				user_birthday);

		Log.e("smardi.Epi", "addedUserUid:" + addedUserUid);

		mPref.setUserBirthday(user_birthday);
		mPref.setUserGender(user_gender);
		mPref.setUserName(user_name);
		mPref.setUserUID((int) addedUserUid);
	}

	protected boolean checkImformation() {
		String user_name = m_name.getText().toString();
		String user_gender = gender;
		String user_birthday = birthday;

		Cursor nameCursor = db_Adapter.getUserList();
		ArrayList<ArrayList<String>> listUser = new ArrayList<ArrayList<String>>();

		while (nameCursor.moveToNext()) {
			ArrayList<String> tempList = new ArrayList<String>();

			tempList.add(nameCursor.getString(0)); // user_name
			tempList.add(nameCursor.getString(1)); // user_gender
			tempList.add(nameCursor.getString(2)); // user_birthday
			tempList.add(nameCursor.getString(3)); // uid

			listUser.add(tempList);
		}

		for (int i = 0; i < listUser.size(); i++) {
			if (user_name.equals(listUser.get(i).get(0))) {
				Toast.makeText(AC_UserAdd.this,
						getString(R.string.userAdd_account_aleady_registered),
						1000).show();
				return false;
			}
		}

		if (user_name.equals("")) {
			Toast.makeText(AC_UserAdd.this,
					getString(R.string.userAdd_input_your_name), 1000).show();
			return false;
		} else if (user_gender == null) {
			Toast.makeText(AC_UserAdd.this,
					getString(R.string.userAdd_select_your_gender), 1000)
					.show();
			return false;
		} else if (user_birthday == null) {
			Toast.makeText(AC_UserAdd.this,
					getString(R.string.userAdd_input_your_birthday), 1000)
					.show();
			return false;
		}

		return true;
	}

	DatePickerDialog.OnDateSetListener dateSetListener = new OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			calDateTime.set(Calendar.YEAR, year);
			calDateTime.set(Calendar.MONTH, monthOfYear);
			calDateTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);

			String strDate;
			strDate = Integer.toString(year) + "-"
					+ Integer.toString(monthOfYear + 1) + "-"
					+ Integer.toString(dayOfMonth);

			String month = "";
			if (monthOfYear + 1 < 10) {
				month = "0" + (monthOfYear + 1);
			}

			String day = "";
			if (dayOfMonth < 10) {
				day = "0" + dayOfMonth;
			} else {
				day = "" + dayOfMonth;
			}
			birthday = year + month + day;

			edit_birth.setText(strDate);
		}
	};
}
